//
//  main.m
//  04-HomeWork-Teacher
//
//  Created by 402030900@qq.com on 16/7/8.
//  Copyright © 2016年 402030900@qq.com. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Color.h"
int main(int argc, const char * argv[]) {
    //1.
    
   NSString * path = @"/Users/402030900qq.com/DLS160710/Objective-C/HomeWork/04-HomeWork-Teacher/04-HomeWork-Teacher/crayons.txt";
    // 通过文件路径,读取文件中的字符
    NSString * resourceString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",resourceString);
    
    // 根据\n切割字符串
    NSArray * colorStringArray = [resourceString componentsSeparatedByString:@"\n"];
    NSLog(@"%@",colorStringArray);
    
    //声明存储颜色的可变字典
    NSMutableDictionary * colorDictionary = [NSMutableDictionary dictionary];
    for (int i = 0; i < colorStringArray.count; i ++) {
        if ([colorStringArray[i] length] > 0) {
         NSArray * color = [colorStringArray[i] componentsSeparatedByString:@" #"];
            [colorDictionary setObject:[color lastObject] forKey:[color firstObject]];
        }
    }
    NSLog(@"%@",colorDictionary);
    
    //2.
    // 创建新字典
    NSMutableDictionary * newColorDictionary = [NSMutableDictionary dictionary];
    //取到老字典中所有key值
    NSArray * allKeys = colorDictionary.allKeys;
    for (int i = 0; i < colorDictionary.allKeys.count; i ++) {
        //取子串
        NSString * subString = [allKeys[i]substringWithRange:NSMakeRange(0, 1)];
        // 通过首字母取出对应的array
        NSMutableArray * colorArray = [newColorDictionary objectForKey:subString];
        // 根据老字典的 key 和 value 生成新的Color对象
        Color * newColor = [[Color alloc]init];
        newColor.colorName = allKeys[i];
        newColor.colorValue = [colorDictionary objectForKey:allKeys];
        // 判断,从新字典中取出的数组是否为空
        // 为空说明,还没有存过对应的首字母的数组
        if (colorArray == nil) {
            // 创建
            colorArray = [NSMutableArray arrayWithObject:newColor];
            //赋值给对应的首字母
            [newColorDictionary setObject:colorArray forKey:subString];
        }else{
            //如果数组不为空,直接添加
            [colorArray addObject:newColor];
        }
    }
    NSLog(@"%@",newColorDictionary);
    return 0;
}
